﻿# -*- coding: utf-8 -*-
import datetime

from openerp import models, fields, api, _
from openerp.exceptions import Warning

class bc_reserve(models.Model):
    _name = 'bc.reserve'

    bussines_id = fields.Many2one('bc.bussines')
    company_id = fields.Many2one('res.company', default=lambda self: self.env.user.company_id)
    resouretype_id = fields.Many2one('bc.resouretype')
    startdate = fields.Date(default=datetime.date.today() + datetime.timedelta(days=1))
    enddate = fields.Date()
    remark = fields.Text()
    state = fields.Selection([('draft', u'草稿'), ('audit', u'审核'), ('close', u'关闭'), ('cancel', u'作废')])

    @api.model
    def create(self, vals):
        vals['state'] = 'draft'
        return super(bc_reserve, self).create(vals)
    
    # 僅能刪除草稿狀態的資料
    @api.multi
    def unlink(self):
       if self.state not in ('draft') :
          raise Warning(_('state {0} can not be delete'.format(self.state)))
       return super(bc_reserve,self).unlink()    

    # 审核
    @api.model
    def btn_audit(self):
        self.write({'state': 'audit', 'audit_uid': self.env.user.id, 'audit_date': datetime.datetime.utcnow()})
        return True

    # 反审核
    @api.model
    def btn_unaudit(self):
        self.write({'state': 'draft', 'audit_uid': False, 'audit_date': False})
        return True

    # 日期防呆
    @api.one
    @api.constrains('enddate', 'startdate')
    def _check_date(self):
        if self.enddate and self.enddate < self.startdate:
            raise ValueError(_("結束日期必須比起始日期還大"))
